package service.impl;

import dao.CartDao;
import dao.ProductDao;
import dao.impl.CartDaoImpl;
import dao.impl.ProductDaoImpl;
import entity.Cart;
import entity.Product;
import service.CartService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.rmi.server.UID;
import java.util.List;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/10/6 18:37
 */
public class CartServiceImpl implements CartService {

    private CartDao cartDao = new CartDaoImpl();
    private ProductDao productDao = new ProductDaoImpl();

    @Override
    public void addCart(int pid, int uid) throws InvocationTargetException, IllegalAccessException {

        //判断商品是否有添加到购物车中
        Cart cart = cartDao.hasCart(pid, uid);

        if (cart != null) {
            //存在就修改数量
            cart.setCnum(cart.getCnum()+1);
            cartDao.updateCart(cart);

        } else {
            //不存在就查询商品对象添加到购物车

            //通过商品ID查询商品
            Product product = productDao.findProductById(pid);

            //创建购物车对象
            cart = new Cart(uid);
            //添加购物车中的商品对象和数量
            cart.setProduct(product);
            cart.setPid(pid);
            cart.setCnum(1);

            //把购物车对象传到Dao层
            cartDao.insertCart(cart);

        }

    }

    /**
     * 查询购物车中的商品
     * @param uid 根据uid查询该用户购物车
     * @return
     */
    @Override
    public List<Cart> findAll(int uid) throws InvocationTargetException, IllegalAccessException {
        return cartDao.findCartByUid(uid);
    }

    /**
     * 删除购物车中单条数据
     * @param cid
     */
    @Override
    public void delCartByCid(int cid) {
        cartDao.deleteCartByCid(cid);
    }

    /**
     * 修改购物车
     * @param cid
     * @param cnum
     * @param price
     */
    @Override
    public void updateCart(int cid, int cnum, int price) {

        BigDecimal count = new BigDecimal(price * cnum);
        cartDao.updateCartByCid(cid, cnum, count);
    }

    /**
     * 清空购物车
     * @param uid
     */
    @Override
    public void clearCart(int uid) {
        cartDao.deleteCartByUid(uid);
    }
}
